package my.servlet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BeanInstanceManager {

	private static final Map<String, Object> beanInstanceMap = new ConcurrentHashMap<String, Object>();

	public synchronized static Object getBeanInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		return getBeanInstance(className, true);
	}

	public synchronized static Object getBeanInstance(String className, boolean singleton) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		if (!singleton) {
			return createInstance(className);
		}
		Object object = beanInstanceMap.get(className);
		if (object == null) {
			object = createInstance(className);
			beanInstanceMap.put(className, object);
		}
		return object;
	}

	private static Object createInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Class<?> c = Class.forName(className);
		return c.newInstance();
	}

}
